package com.zmn.plat.admin.controller.message.config;

import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import com.zmn.common.dto2.ResponseDTO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.cas.model.LoginStaff;
import com.zmn.plat.admin.controller.message.MsgTemplateBaseController;
import com.zmn.plat.manager.constant.MsgTemplateConsts;
import com.zmn.plat.common.exception.PlatException;
import com.zmn.plat.model.entity.message.MsgTemplateConfig;
import com.zmn.plat.model.entity.message.MsgTemplateConfigQuery;

/**
 * 描述: 消息管理配置修改Controller
 *
 * @auther tanghongjun
 * @since 2019/10/21 16:36
 */
@Controller
@RequestMapping("/msg/temp/conf/")
public class MsgTemplateConfigModifyController extends MsgTemplateBaseController {
    private Logger logger = LoggerFactory.getLogger(MsgTemplateConfigModifyController.class);

    /**
     * region 新增/修改
     *
     * @param templateId
     *            模板ID
     * @param cityIds
     *            城市ID集合
     * @return ModelAndView 执行结果
     */
    @RequestMapping(value = "saveCityConfig")
    @RequiresPermissions("/msg/temp/addEdit.action")
    @ResponseBody
    public ResponseDTO saveCityConfig(HttpServletRequest request, @RequestParam(value = "templateId") Integer templateId,
                                      @RequestParam(value = "cityIds[]") List<Integer> cityIds) {
        String lable = "保存模板城市配置";
        try {
            if (NumberUtil.isNullOrZero(templateId)) {
                return ResponseDTO.fail("模板ID不能为空！");
            }
            msgTemplateConfigService.saveByTempateIdAndCityIds(templateId, cityIds, getMcStaff().getRealName());
            return ResponseDTO.success(lable + "成功！");
        } catch (Exception ex) {
            logger.error(String.format("[zmn]新增/修改模板组失败,servProductVO:[%s],ex:[%s]", ex, ex.getMessage()));
            return ResponseDTO.fail(lable + "失败！");
        }
    }

    /**
     * 新增渠道配置
     *
     * @param ids
     *            the ids
     * @param templateId
     *            模板ID
     * @return the result dto
     * @author xiangjunming
     * @since 2019/10/29
     */
    @RequestMapping(value = "addChannelConfig")
    @RequiresPermissions("/msg/temp/addEdit.action")
    @ResponseBody
    public ResponseDTO addChannelConfig(String ids, @RequestParam("id") Integer templateId) {
        if (StringUtil.isBlank(ids)) {
            return ResponseDTO.fail("请选择渠道！");
        }
        if (templateId == null || templateId == 0) {
            return ResponseDTO.fail("模板ID不能为空！");
        }
        LoginStaff mcStaff = getMcStaff();
        List<Integer> channelIds = StringUtil.convertStrsToList(ids);
        try {
            MsgTemplateConfigQuery query = new MsgTemplateConfigQuery();
            query.setTemplateId(templateId);
            query.setBusinessType(MsgTemplateConsts.MSG_TEMP_TYPE_CHANNEL);
            List<MsgTemplateConfig> msgTemplateConfigs = msgTemplateConfigService.listByQuery(query);
            List<Integer> configChannelIds =
                msgTemplateConfigs.stream().map(MsgTemplateConfig::getBusinessId).distinct().collect(Collectors.toList());

            // 渠道ID去重
            channelIds = channelIds.stream().filter(p -> !configChannelIds.contains(p)).collect(Collectors.toList());

            if (channelIds.size() == 0) {
                return ResponseDTO.fail("数据已存在! 不需要填加");
            }

            List<MsgTemplateConfig> configs = channelIds.stream().map(channelId -> {
                MsgTemplateConfig config = new MsgTemplateConfig();
                config.setBusinessId(channelId);
                config.setTemplateId(templateId);
                config.setBusinessType(MsgTemplateConsts.MSG_TEMP_TYPE_CHANNEL);
                config.setCreater(mcStaff.getRealName());
                config.setCreateTime(DateUtil.getNow());
                return config;
            }).collect(Collectors.toList());

            msgTemplateConfigService.insertBatch(configs);
        } catch (PlatException e) {
            return ResponseDTO.fail(e.getMessage());
        } catch (Exception e) {
            logger.error("error:", e);
            return ResponseDTO.fail("系统错误! 操作失败!");
        }

        return ResponseDTO.success(true,"操作成功！");
    }

    /**
     * 移除渠道配置
     *
     * @param ids
     *            the ids
     * @return the result dto
     * @author xiangjunming
     * @since 2019/10/29
     */
    @RequestMapping(value = "delChannelConfig")
    @RequiresPermissions("/msg/temp/addEdit.action")
    @ResponseBody
    public ResponseDTO delChannelConfig(String ids) {
        if (StringUtil.isBlank(ids)) {
            return ResponseDTO.fail("请选择渠道！");
        }
        try {
            msgTemplateConfigService.deleteBatch(StringUtil.convertStrsToList(ids));
        } catch (PlatException e) {
            return ResponseDTO.fail(e.getMessage());
        } catch (Exception e) {
            logger.error("error:", e);
            return ResponseDTO.fail("系统错误! 操作失败!");
        }

        return ResponseDTO.success(true,"操作成功！");
    }
}
